package web

import (
	"bytes"
	"context"
	"gitee.com/alex-pistachio/axel/logs"
	"github.com/cloudwego/hertz/pkg/app"
	"github.com/hertz-contrib/requestid"
	"github.com/jefferyjob/go-easy-utils/byteUtil"
	"github.com/sirupsen/logrus"
	"time"
)

var postMethod = []byte("POST")

func RestAccessLog() app.HandlerFunc {
	return func(c context.Context, ctx *app.RequestContext) {

		var fields *logrus.Fields

		if bytes.Equal(ctx.Request.Method(), postMethod) {
			data := byteUtil.BytesToStr(ctx.Request.Body())

			fields = &logrus.Fields{
				"req_id": requestid.Get(ctx),
				"method": byteUtil.BytesToStr(ctx.Request.Header.Method()),
				"path":   byteUtil.BytesToStr(ctx.Request.URI().PathOriginal()),
				"ip":     ctx.ClientIP(),
				"body":   data,
			}
		} else {
			fields = &logrus.Fields{
				"req_id": requestid.Get(ctx),
				"method": byteUtil.BytesToStr(ctx.Request.Header.Method()),
				"path":   byteUtil.BytesToStr(ctx.Request.URI().PathOriginal()),
				"ip":     ctx.ClientIP(),
			}
		}

		logs.Logger().WithFields(*fields).Info("Before request")

		start := time.Now()
		ctx.Next(c)
		end := time.Now()
		latency := end.Sub(start).Microseconds
		b := ctx.Response.Body()

		logs.Logger().WithFields(logrus.Fields{
			"req_id":   requestid.Get(ctx),
			"status":   ctx.Response.StatusCode(),
			"cost(us)": latency(),
			"method":   byteUtil.BytesToStr(ctx.Request.Header.Method()),
			"path":     byteUtil.BytesToStr(ctx.Request.URI().PathOriginal()),
			"ip":       ctx.ClientIP(),
			"response": byteUtil.BytesToStr(b),
		}).Info("After request")
	}
}
